import React, { useState, useEffect, useRef } from 'react'
import { Table, Button, Tag, Space, Modal, Form, Input, Radio, Popconfirm, notification, message } from 'antd'
import { EditOutlined, DeleteOutlined } from  '@ant-design/icons'
import { getAdminlist, addAdmin, deleteAdmin, updateAdmin } from '../../api/admin'

function Adminlist() {

  const [ adminlist, setAdminlist ] = useState([])

  const [ addVisible, setAddVisible ] = useState(false)
  const [ updateVisible, setUpdateVisible] = useState(false)

  useEffect(() => {
    async function fetchData() {
      const res = await getAdminlist()
      setAdminlist(res.data.data)
    }
    fetchData()
  },[])


  // 添加管理员
  const addRef = useRef()
  const addHandleOk = () => { setAddVisible(false)}
  const addHandleCancel = () => { setAddVisible(false)}
  const onAddFinish = async (values) => { 
    const res = await addAdmin(values)
    // 管理员账户存在
    if (res.data.code === '10006') {
      // message.warning('该管理员账号已存在')
      notification.warning({
        message: '添加管理员提示信息',
        description:
          '该管理员账号已存在',
      });
    } else {
      // 关闭添加模态框
      setAddVisible(false)
      // 更新表格的数据
      // 1.const arr = [...adminlist, values] 
      // 有缺陷:values缺少adminid 会报key值不唯一的warning
      // 2.深拷贝数据,push进去新添加的数据
      // const arr = JSON.parse(JSON.stringify(adminlist))
      // arr.push(res.data.data[0])
      // 3.扩展运算符合并数据
      const arr = [...adminlist, ...res.data.data]
      setAdminlist(arr)
      message.success('添加管理员成功')
      // 重置模态框的内容
      addRef.current.setFieldsValue({
        adminname: '',
        password: '',
        role: 0
      })
    }
  }
  
  // 删除管理员
  const confirm = async (record) => {
    await deleteAdmin({ adminid: record.adminid })
    const arr = JSON.parse(JSON.stringify(adminlist))
    const index = arr.findIndex(item => item.adminname === record.adminname)
    arr.splice(index, 1)
    setAdminlist(arr)
    message.success('删除管理员成功')
  }
  
  // 修改管理员
  const updateRef = useRef()
  const updateHandleOk = () => { setUpdateVisible(false)}
  const updateHandleCancel = () => { setUpdateVisible(false)}
  const onEditAdminInfo = (record) => {
    updateRef.current.setFieldsValue({
      adminname: record.adminname,
      role: record.role
    })
  }
  const onUpdateFinish = async (values) => {
    await updateAdmin(values)
    setUpdateVisible(false)
    // 寻找当前要更新角色的用户所在数组的索引
    const index = adminlist.findIndex(item => item.adminname === values.adminname)
    const arr = JSON.parse(JSON.stringify(adminlist))
    // 更新指定索引用户的角色信息
    arr[index].role = values.role
    setAdminlist(arr)  
    message.success('更新管理员成功')  
  }

  const columns = [
    {
      title: '序号',
      render: (text, record, index) => (<span>{ index + 1 }</span>)
    },
    { 
      title: '管理员账号',
      dataIndex: 'adminname',
      key: 'adminname'
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (text, record, index) => {
        return (
          <>
          { text === 2 ? <Tag color="green">超级管理员</Tag> : <Tag color="geekblue">管理员</Tag>}
          </>
        )
      }
    },
    {
      title: '操作',
      render: (text, record, index) => {
        return record.adminname === 'admin' ? null : <Space>
            <Button type="primary" shape="circle" icon={<EditOutlined/>} 
              onClick={ () => {
                setUpdateVisible(true)
                setTimeout(() => { onEditAdminInfo(record)}, 0)
              }}
            />
            <Popconfirm
              title="你确定要删除该管理员?"
              onConfirm={() => { confirm(record)}}
              onCancel={() => {}}>
              <Button type="primary" danger shape="circle" icon={<DeleteOutlined/>} />
            </Popconfirm>
          </Space>
      }
    }
  ]

  return (
    <>
      <Button type="primary" style={{ marginBottom:10 }} onClick={() => setAddVisible(true)}>
        添加管理员
      </Button>
      <Table dataSource={adminlist} columns={columns} rowKey={(record) => record.adminid} pagination={{
        defaultCurrent: 1,
        defaultPageSize: 4
      }}/>
      <Modal
        title="添加管理员"
        visible={addVisible}
        onOk={addHandleOk}
        onCancel={addHandleCancel}
        footer={null}
      >
        <Form name="add" onFinish={onAddFinish} ref={addRef}>
          <Form.Item
            name="adminname"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="管理员用户名"/>
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="管理员密码"/>
          </Form.Item>
          <Form.Item 
            name="role"
            rules={[{ required: true, message: '请选择权限' }]}>
            <Radio.Group>
              <Radio.Button value={1}>管理员</Radio.Button>
              <Radio.Button value={2}>超级管理员</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              添加
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="修改管理员"
        visible={updateVisible}
        onOk={updateHandleOk}
        onCancel={updateHandleCancel}
        footer={null}
      >
        <Form name="update" onFinish={onUpdateFinish} ref={updateRef}>
          <Form.Item
            name="adminname"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="管理员用户名" disabled/>
          </Form.Item>
          <Form.Item 
            name="role"
            rules={[{ required: true, message: '请选择权限' }]}>
            <Radio.Group>
              <Radio.Button value={1}>管理员</Radio.Button>
              <Radio.Button value={2}>超级管理员</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              更新
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default Adminlist
